package com.nondo.rdp.finance.endpoint.api.admin;

import com.nondo.rdp.auth.service.UserService;
import com.nondo.rdp.core.common.ValidateUtil;
import com.nondo.rdp.core.domain.Rules;
import com.nondo.rdp.core.model.View;
import com.nondo.rdp.core.service.RulesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController("apiAdminRules")
@RequestMapping("/api/admin/rules")
public class RulesEndpoint {
    @Autowired
    RulesService rulesService;

    @Autowired
    UserService userService;

    @RequestMapping("/list")
    public View list() {
        View view = new View(20000, "获取列表成功");

        List list = rulesService.findAll();

        view.setData(list);

        return view;
    }

    @RequestMapping("/add")
    public View add(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Rules rules, BindingResult result) {
        View view = new View(20000, "添加成功");

        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        } else {
            //检查规则名是否已经存在
            Rules rulesFind = this.rulesService.findByType(rules.getType());
            if (rulesFind != null) {
                return View.ofError("已存在的规则名");
            }

            this.rulesService.save(rules);
            view.setData(rules);
        }
        return view;
    }

    @RequestMapping("/update")
    public View update(HttpServletRequest request, HttpServletResponse response, @Validated @RequestBody Rules rules, BindingResult result) {
        View view = new View(20000, "更新成功");

        if (result.hasErrors()) {
            return View.ofError(ValidateUtil.first(result.getAllErrors()));
        } else {
            //检查规则名是否已经存在
            Rules rulesFind = this.rulesService.findByType(rules.getType());
            if (rulesFind != null && !rulesFind.getId().equals(rules.getId())) {
                return View.ofError("已存在的规则名");
            }
            this.rulesService.save(rules);
        }

        return view;
    }
}